<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>系统角色</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link rel="stylesheet" href="../../../lib/layui-v2.5.5/css/layui.css" media="all">
		<link rel="stylesheet" href="../../../css/public.css" media="all">
	</head>
	<body>
		<div class="layuimini-container">
			<div class="layuimini-main">
				<!--搜索开始-->
				<fieldset class="layui-elem-field layuimini-search">
					<legend>搜索信息</legend>
					<div style="margin: 10px 10px 10px 10px">
						<form class="layui-form layui-form-pane" action="" id="searchFrm">
							<div class="layui-form-item">
								<div class="layui-inline">
									<label class="layui-form-label">角色名称</label>
									<div class="layui-input-inline">
										<input type="text" name="name" autocomplete="off" class="layui-input">
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">角色备注</label>
									<div class="layui-input-inline">
										<input type="text" name="remark" autocomplete="off" class="layui-input">
									</div>
								</div>
								<div class="layui-inline">
									<a class="layui-btn " lay-submit="" lay-filter="data-search-btn"><label class="layui-icon layui-icon-search"></label>搜索</a>
									<a class="layui-btn layui-btn-warm" onclick="javascript:$('#searchFrm')[0].reset()" lay-filter="data-search-btn"><label
										 class="layui-icon layui-icon-refresh"></label>重置</a>
								</div>
							</div>
						</form>
					</div>
				</fieldset>
				<!--搜索结束-->

				<!--表格开始-->
				<table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
				<script type="text/html" id="roleToolBar">
					<a class="layui-btn layui-btn-sm" lay-event="add">添加</a>
            <a class="layui-btn layui-btn-sm layui-btn-danger data-count-delete" lay-event="batchdelete">批量删除</a>
        </script>
				<script type="text/html" id="roleTableBar">
					<a class="layui-btn layui-btn-xs layui-btn-warm data-count-delete" lay-event="update">修改</a>
		    <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
			<a class="layui-btn layui-btn-xs layui-btn-warm data-count-delete" lay-event="selectMenu">分配权限</a>
		</script>
				<script type="text/html" id="availableTpl">
					<!-- 这里的 checked 的状态只是演示 -->
		  <input type="checkbox" name="available" value="{{d.id}}" lay-skin="switch" lay-text="可用|不可用" lay-filter="availableSwitch" {{ d.available == 1 ? 'checked' : '' }}>
		</script>
				<!--表格结束-->

				<!--添加和修改的弹出层开始-->
				<div id="addOrUpdateDiv" style="display: none;padding: 0.3125rem">
					<form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm" id="dataFrm">
						<div class="layui-form-item">
							<label class="layui-form-label">角色名称</label>
							<div class="layui-input-block">
								<input type="hidden" name="id" />
								<input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input">
							</div>
						</div>
						<div class="layui-form-item">
							<label class="layui-form-label">角色备注</label>
							<div class="layui-input-block">
								<textarea placeholder="请输入角色备注" name="remark" class="layui-textarea"></textarea>
							</div>
						</div>
						<div class="layui-form-item">
							<div class="layui-input-block" style="text-align: center;">
								<a class="layui-btn " lay-submit="" lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
								<a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label
									 class="layui-icon layui-icon-refresh"></label>重置</a>
							</div>
						</div>
					</form>
				</div>
				<!--添加和修改的弹出层结束-->

				<!--选择菜单和权限的弹出层开始-->
				<div id="selectMenuDiv" style="display: none;padding: 0.3125rem;">
					<table class="layui-hide" id="menuTable" lay-filter="menuTable"></table>
				</div>
				<!--选择菜单和权限的弹出层结束-->

			</div>
		</div>
		<script src="../../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
		<script src="../../../lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
		<script src="../../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
		<script src="../../../lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>
		<script src="../../../lib/common/jquery.cookie.min.js" charset="utf-8"></script>
		<script src="../../../lib/common/common.js" charset="utf-8"></script>

		<script>
			layui.use(['form', 'table', 'laydate', 'layer', 'treeTable'], function() {
				var form = layui.form;
				var table = layui.table;
				var laydate = layui.laydate;
				var layer = layui.layer;
				var treeTable = layui.treeTable;

				var tableIns = table.render({
					elem: '#roleTable',
					url: api + 'role/loadAllRole',
					toolbar: "#roleToolBar",
					cellMinWidth: true,
					cols: [
						[{
								type: "checkbox",
								fixed: "left"
							},
							{
								field: 'id',
								title: 'ID',
								align: "center"
							},
							{
								field: 'name',
								title: '角色标题',
								align: "center"
							},
							{
								field: 'remark',
								title: '角色备注',
								align: "center"
							},
							{
								field: 'available',
								title: '是否可用',
								align: "center",
								width: 120,
								templet: '#availableTpl'
							},
							{
								field: 'createtime',
								title: '创建时间',
								align: "center"
							},
							{
								title: '操作',
								templet: '#roleTableBar',
								fixed: "right",
								align: "center"
							}
						]
					],
					page: true
				});

				// 监听搜索操作
				form.on('submit(data-search-btn)', function(data) {
					var params = $("#searchFrm").serialize();
					//执行搜索重载
					table.reload('roleTable', {
						page: {
							curr: 1
						},
						url: api + 'role/loadAllRole?' + params
					});
					return false;
				});

				//监听表头的事件
				table.on('toolbar(roleTable)', function(obj) {
					var checkStatus = table.checkStatus(obj.config.id);
					switch (obj.event) {
						case 'batchdelete':
							batchdelete();
							break;
						case 'add':
							openAddRole();
							break;
					};
				});

				//监听行数据的事件
				table.on('tool(roleTable)', function(obj) {
					var data = obj.data;
					if (obj.event === 'delete') {
						layer.confirm('真的删除【' + data.name + '】这个角色吗么', function(index) {
							$.post(api + "role/deleteRole", {
								id: data.id
							}, function(res) {
								layer.msg(res.msg);
								obj.del();
								layer.close(index);
							})
						});
					} else if (obj.event === 'update') {
						openUpdateRole(data);
					} else if (obj.event === 'selectMenu') {
						openSelectMenu(data);
					}
				});
				
				
				
				//监听可用操作
				form.on('switch(availableSwitch)', function(obj) {
					layer.load(0, {
						time: 1500
					});
					$.post(api + "role/updateRole", {
						id: this.value,
						available: obj.elem.checked ? 1 : 0
					}, function(res) {
						layer.msg(res.msg);
						tableIns.reload();
					})
				});

				//打开添加角色的弹层
				var mainIndex;
				var url; //动态的url
				function openAddRole() {
					mainIndex = layer.open({
						type: 1,
						title: '添加角色',
						content: $("#addOrUpdateDiv"),
						area: ['800px', '500px'],
						success: function(index) {
							url = api + "role/addRole";
							//重置表单
							$("#dataFrm")[0].reset();
						}
					});
				}

				// 打开修改角色弹出窗
				function openUpdateRole(data) {
					mainIndex = layer.open({
						type: 1,
						title: '修改【' + data.name + '】角色',
						content: $("#addOrUpdateDiv"),
						area: ['800px', '600px'],
						success: function(index) {
							url = api + "role/updateRole";
							//装载数据表格
							form.val("dataFrm", data);
						}
					});
				}
				
				
				//提交数据
				form.on("submit(doSubmit)", function(data) {
					var params = $("#dataFrm").serialize();
					layer.load(0, {
						time: 1500
					});
					$.post(url, params, function(res) {
						layer.msg(res.msg);
						if (res.code == 200) {
							tableIns.reload();
						}
						layer.close(mainIndex);
					})
					return false;
				});

				//打开选择菜单和权限的弹出层
				function openSelectMenu(data_table) {
					// 定义treeTable变量
					var table_MenusIns;
					
					mainIndex = layer.open({
						type: 1,
						title: '分配【' + data_table.name + '】角色和权限和菜单',
						content: $("#selectMenuDiv"),
						area: ['800px', '600px'],
						btn: ['<span class="layui-icon layui-icon-ok">确认分配</span>'],
						btnAlign: 'c',
						yes: function(indexs,layero) {
							layer.prompt({
								formType: 1,
								value: '',
								maxlength: 6, //可输入文本的最大长度，默认500
								title: '敏感操作，请输入口令，防止杂毛',
							}, function(value, index, elem) {
								if (value == 'yby123') {
									layer.load(0, {
										time: 1500
									});
									// 获取treeTable选中的数据
									var m = table_MenusIns.checkStatus();
									
									// 循环该数据 拼接字符串
									var rid = data_table.id;
									var params = "rid="+rid;
									$.each(m,function(index,value){
										params+="&mids="+value.id;
									})
									console.log(params);
									// 保存角色菜单权限
									$.post(api+"role/saveRoleMenu",params,function(res){
										layer.msg(res.msg);
										layer.close(indexs);
										layer.close(index);
									})
								} else {
									layer.msg("口令错误");
								}
							});
							
						},
						success: function(index) {
							table_MenusIns = treeTable.render({
								tree: {
									iconIndex: 1, // 折叠图标显示在第几列
									idName: 'id', // 自定义id字段的名称
									pidName: 'pid', // 自定义标识是否还有子节点的字段名称
									isPidData: true, // 是否是pid形式数据
									openName: 'spread' // 自定义默认展开的字段名
								},
								elem: '#menuTable',
								cellMinWidth: true,
								cols: [{
										type: "checkbox"
									},
									{
										field: 'title',
										title: '菜单或权限名称'
									},
									{field: 'id',  title: 'ID'},
									{
										field: 'type',
										title: '类型',
										align: "center",
										templet: function(d) {
											if (d.type == 'topmenu') {
												return '<span class="layui-badge layui-bg-red">顶部菜单</span>';
											}
											if (d.type == 'leftmenu') {
												return '<span class="layui-badge layui-bg-blue">左侧菜单</span>';
											} else {
												return '<span class="layui-badge layui-bg-molv">权限</span>';
											}
										}
									}
								],
								text: 
								{
								        none: '<div style="padding: 18px 0;">哎呀，一条数据都没有~</div>'
								},
								reqData: function(data, callback) {
									if (data == undefined) {
										// 在这里写ajax请求，通过callback方法回调数据
										$.get(api + 'menu/loadAllMenu?available=1', function(res) {
											callback(res.data); // 参数是数组类型
											//选择中已选择的权限或菜单
											$.get(api + "role/queryMenuIdsByRid", {
												id: data_table.id
											}, function(rs) {
												// console.log(rs.data);//[1,3,8]
												
												var x = new Array();
												
												// 循环当前加载的所有菜单
												$.each(res.data,function(index,value){
													// console.log(index)
													// console.log(value)
													// 循环当前角色拥有的菜单 反选
													$.each(rs.data,function(r_index,r_value){
														// 根据所有菜单的id 进行判断 是否等于 选择的菜单id
														if(value.id==r_value){
															// 然后进行判断是否有子节点
															if(!value.children){
																console.log(r_value)
																x.push(r_value)
															}
														}
													})
												})
												// console.log(x)
												
												table_MenusIns.setChecked(x); // 设置选中数据
											});
										});
									} else {
										callback([]); //回调一个空数据去渲染表格 
									}
								}
							});
						}
					});
				}

				//批量删除
				function batchdelete() {
					var checkStatus = table.checkStatus('roleTable'); //idTest 即为基础参数 id 对应的值
					var data = checkStatus.data;
					var length = checkStatus.data.length;
					console.log(checkStatus.data) //获取选中行的数据
					console.log(checkStatus.data.length) //获取选中行数量，可作为是否有选中行的条件
					if (length == 0) {
						layer.msg("请选中要删除的行数据");
					} else {
						layer.prompt({
							formType: 1,
							value: '',
							maxlength: 6, //可输入文本的最大长度，默认500
							title: '正在批量删除角色，敏感操作，请输入口令，防止杂毛',
						}, function(value, index, elem) {
							if (value == 'yby123') {
								layer.load(0, {
									time: 1500
								});
								var params = "";
								$.each(data, function(index, item) {
									if (index == 0) {
										params += "ids=" + item.id;
									} else {
										params += "&ids=" + item.id;
									}
								});

								// 执行删除
								$.post(api + "role/batchDeleteRole", params, function(res) {
									layer.msg(res.msg);
									tableIns.reload();
									layer.close(index);
								});
							} else {
								layer.msg("口令错误");
							}
						});

					}
				}
			});
		</script>
		<script>

		</script>

	</body>
</html>
